package com.huonan.component.es;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.List;
import java.util.Set;

public class SourceFields {
    /**
     * 按自定义格式要求导出字段
     *
     * @param newObj 导出 JSONObject
     * @param source 导出字段
     */
    public static void customSource(JSONObject newObj, String source) {
        List<String> list = FileUtil.readUtf8Lines("/Users/lxp/IdeaProjects/Study/MainTest/data/field.txt");
        JSONObject sourceObj = JSONUtil.parseObj(source);
        Set<String> keys = sourceObj.keySet();
        JSONConfig jsonConfig = new JSONConfig().setIgnoreNullValue(false);
        JSONObject dataObj = new JSONObject(jsonConfig);
        for (String f : list) {
            Object value;
            String[] s = f.split(",");
            String key = s[0];
            String keyType = s[1];
            if (keyType.equals("nested")) {
                value = sourceObj.getJSONArray(key);
            } else if (keyType == "kw") {
                value = sourceObj.getStr(key);
            } else if (keyType == "double") {
                value = sourceObj.getDouble(key);
            } else if (keyType == "long") {
                value = sourceObj.getLong(key);
            } else {
                value = sourceObj.getObj(key);
            }
//            if (value != null) {
//                if (Integer.parseInt(value) < 0) {
//                    dataObj.putOnce(key, null);
//                }
//            }
            newObj.putOnce(key, value);
        }
//
    }

    /*导出CSV格式*/
    public static void customCSVSource(StringBuilder sb, String source) {
        JSONObject sourceObj = JSONUtil.parseObj(source);
        Set<String> keys = sourceObj.keySet();
        for (String key : keys) {
            String value = sourceObj.getStr(key);
            if (value != null) {
                sb.append(value).append("&");
            } else {
                sb.append("&");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
            sb.deleteCharAt(sb.length() - 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }

    /**
     * 默认导出字段
     *
     * @param newObj 导致字段组装为 Json
     * @param source 导致原字段
     */
    public static void defaultExtractSource(JSONObject newObj, String source) {
        String newKey = "kw_dataTagPlus";
        JSONArray array = new JSONArray();
        array.add("KOC");
        newObj.putOnce(newKey, array);
    }

    public static void exportSource(JSONObject newObj, String source) {
        JSONObject sourceObj = JSONUtil.parseObj(source);
        Set<String> keys = sourceObj.keySet();
        for (String key : keys) {
            String value = sourceObj.getStr(key);
            newObj.putOnce(key, value);
        }
    }
}
